/*
 * Copyright 2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mx.ymate.modbus.impl;

import com.digitalpetri.modbus.slave.ServiceRequestHandler;
import com.mx.ymate.dev.util.ConfigUtil;
import com.mx.ymate.modbus.IModbus;
import com.mx.ymate.modbus.IModbusConfig;
import net.ymate.platform.core.configuration.IConfigReader;
import net.ymate.platform.core.module.IModuleConfigurer;

/**
 * @Author: mengxiang.
 * @Date 2025/11/10.
 * @Time: 16:00.
 * @Description:
 */
public final class DefaultModbusConfig implements IModbusConfig {

    private boolean enabled;
    private boolean autoStart;
    private String host;
    private int port;
    private ServiceRequestHandler serviceRequestHandler;
    private boolean initialized;


    public static DefaultModbusConfig create(IModuleConfigurer moduleConfigurer) {
        return new DefaultModbusConfig(moduleConfigurer);
    }


    private DefaultModbusConfig() {
    }

    private DefaultModbusConfig(IModuleConfigurer moduleConfigurer) {
        //对于不能自动装配的参数进行设置
        IConfigReader configReader = moduleConfigurer.getConfigReader();
        ConfigUtil configUtil = new ConfigUtil(configReader.toMap());
        enabled = configUtil.getBool(ENABLED, true);
        host = configUtil.getString(HOST,"0.0.0.0");
        port = configUtil.getInt(PORT, 502);
        autoStart = configUtil.getBool(AUTO_START, true);
        serviceRequestHandler = configUtil.getClassImpl(SERVICE_REQUEST_HANDLER,ServiceRequestHandler.class);
        if(serviceRequestHandler == null){
            serviceRequestHandler = new DefaultServiceRequestHandler();
        }
    }

    @Override
    public void initialize(IModbus owner) throws Exception {
        if (!initialized) {
            initialized = true;
        }
    }

    @Override
    public boolean isInitialized() {
        return initialized;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @Override
    public boolean isAutoStart() {
        return autoStart;
    }

    @Override
    public String host() {
        return host;
    }

    @Override
    public int port() {
        return port;
    }

    @Override
    public ServiceRequestHandler serviceRequestHandler() {
        return serviceRequestHandler;
    }
}